/**
 * Created by user on 2015/9/21.
 */

var async = require('async');
var mysqlUtil = require('../../../common/utils/mysqlUtil');
var Card = mongoose.model('card');
var User = mongoose.model('user');
var Community = mongoose.model('community');
var toolUtil = require('../../../common/utils/toolUtil');

exports.cardListService = function(req ,callback) {

    var body = req.body;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    var paged = (req.params.size && req.params.page);

    var option = body;
    //var sortType = paged ? {endDate:-1} : {};

    if (option.title) option.title = new RegExp(option.title);
    logger.debug(option);
    async.series([

        function (callbackInner) {
            Card.count(option, function (err, count) {

                if (err) {
                    callbackInner(err, null);
                }else {
                    var temp = {count: count, totalPage:Math.ceil(count/size)};
                    callbackInner(err, temp);
                }
            });
        },
        function (callbackInner) {

            Card.find(option).sort({beginDate:-1}).skip(index).limit(size)
                .populate('province', '_id name')
                .populate('city', '_id name')
                .populate('county', '_id name')
                .exec(function (err, results) {

                    if (err) {
                        callbackInner(err);
                    } else {
                        callbackInner(null, results);
                    }
                });

        }], callback);

};

exports.cardAddService = function(req ,callback) {

    var body = req.body;
    //logger.debug(body);
    var data = {
        title : body.title
        ,desc : body.desc
        ,url: body.url
        ,contentId : body.contentId
        ,openType :body.openType
        ,level : body.level
        ,beginDate : body.beginDate
        ,endDate : body.endDate
    };

    if(data.url){
        data.url = data.url.replace('&source=card','');
        data.url = data.url.replace('?source=card','');

        //if(data.url.indexOf('?')>0){
        //    data.url += '&source=card';
        //}else{
        //    data.url += '?source=card';
        //};
    };

    if (body.provinceId)  data.province = body.provinceId;
    if (body.cityId)  data.city = body.cityId;
    if (body.countyId)  data.county = body.countyId;
    if (body.imageURL) data.imageURL = body.imageURL;
    if (body.cardOrder) data.cardOrder = body.cardOrder;
    logger.debug(data);


    var temp = new Card(data);
    temp.save(callback);


};

exports.cardDeleteService = function (req, callback) {

    var ids = req.body.cardID;

    var cardIn = {};
    cardIn["$in"] = [];
    for (var i = 0, l = ids.length; i < l; i++) {
        cardIn["$in"].push(ids[i]);
    }
    logger.debug(cardIn);
    Card.remove({_id :cardIn}, callback);
};

exports.cardEditService = function(req ,callback) {

    var body = req.body;

    //if (!(body.provinceId && body.cityId && body.countyId && body.city && body.communityName && body.communityAddress)) {
    //    return callback("缺少小区基础数据",null);
    //}
    if(body.card.url){
        body.card.url = body.card.url.replace('&source=card','');
        body.card.url = body.card.url.replace('?source=card','');

        if(body.card.url.indexOf('?')>0){
            body.card.url += '&source=card';
        }else{
            body.card.url += '?source=card';
        };
    };

   logger.debug(body);

    Card.update({_id: body.cardID}, body.card, callback);
};

exports.cardPushService = function (req, callback){

    var input = req.body;

    if(input.url){
        input.url = input.url.replace('&source=card','');
        input.url = input.url.replace('?source=card','');

        if(input.url.indexOf('?')>0){
            input.url += '&source=notify';
        }else{
            input.url += '?source=notify';
        };
    };

    var option = input.pushCommunity;
    logger.debug(option);

    if(Number(input.level) ==2 || Number(input.level) ==1 || Number(input.level) ==0) {

        var tag = '';

        switch (Number(input.level)){
            case 0:
                tag = 'all'
                break;
            case 1:
                tag = input.pushCommunity.provinceId;
                break;
            case 2:
                tag = input.pushCommunity.cityId;
                break;
        };


        var pushData = {
            //tags: input.tags,
            //content: content,
            type: 1,
            flag: 2,
            openType: input.openType,
            contentId: input.contentId,
            //createdBy: input.createdBy,
            ds: input.desc,
            url: input.url,
            ip: req.headers['X-Real-IP'],
            tag: tag,
            type: 'operate',
            msgType: 'banner_push'
        };
        logger.debug(pushData);
        toolUtil.putMessageTagPushMQ(pushData);

        callback(null,{});

    }else {
        Community.find(option, function (err, result) {
            //遍历小区
            async.eachSeries(result, function (community, callbackInner) {

                User.find({community: community}).exec(function (err, result) {

                    if(result) {
                        var userList = [];
                        if (result) {
                            for (user in result) {
                                userList.push(result[user]._id);
                            }
                            ;

                        };

                        var content = {
                            type: 1,
                            flag: 2,
                            openType: input.openType,
                            contentId: input.contentId,
                            //createdBy: input.createdBy,
                            desc: input.desc,
                            url: input.url
                        };
                        var pushData = {
                            uList: userList,
                            content: content,
                            ip: req.headers['X-Real-IP'],
                            tag: input.tag,
                            type: 'operate',
                            msgType: 2
                        };
                        toolUtil.putMessageGetuiPushMQ(pushData);
                    }
                    callbackInner(err, {});
                });

            }, function (err) {
                callback(err, null);
            });


        });
    };
};